﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.Approval;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.Approval
{
    /// <summary>
    /// 审批请假
    /// </summary>
    public class ApprovalLeaveCommandHandler : IRequestHandler<ApprovalLeaveCommand, APIResult<object>>
    {
        private readonly IBaseRepository<LeaveApplication> leaveappRep;
        private readonly IBaseRepository<ApprovalRecord> recordRep;
        private readonly IBaseRepository<User> userRep;

        public ApprovalLeaveCommandHandler(IBaseRepository<LeaveApplication> leaveappRep, IBaseRepository<ApprovalRecord> recordRep, IBaseRepository<User> userRep)
        {
            this.leaveappRep = leaveappRep;
            this.recordRep = recordRep;
            this.userRep = userRep;
        }

        public async Task<APIResult<object>> Handle(ApprovalLeaveCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<object>();

            try
            {
                // 1. 获取申请并锁定记录
                var application =  leaveappRep.GetAll().Result
                    .FirstOrDefault(x => x.LeaveId == request.LeaveId);

                if (application == null)
                {
                    result.Code = APIEnum.操作失败;
                    result.Msg = "未找到对应的请假申请";
                    return result;
                }

                // 2. 检查是否已审批过
                var existingApproval =  recordRep.GetAll().Result
                    .Any(x => x.LeaveId == request.LeaveId
                                && x.ApproverId == request.userId);

                if (existingApproval)
                {
                    result.Code = APIEnum.操作失败;
                    result.Msg = "您已审批过该申请";
                    return result;
                }

                // 3. 创建审批记录
                var record = new ApprovalRecord
                {
                    LeaveId = request.LeaveId,
                    ApproverId = request.userId,
                    Status = request.Status,
                    ApprovalTime = DateTime.Now,
                    ApproverName = request.NickName,
                    DepartmentHeadId = request.DepartmentHeadId,
                    DepartmentId = request.DepartmentId,
                    Comment = request.Comment
                };

                await recordRep.Add(record);

                // 4. 部门领导审批逻辑
                if (request.DepartmentHeadId == 1)
                {
                    // 获取部门领导总数
                    var totalLeaders =  userRep.GetAll().Result
                        .Count(x => x.DepId == request.DepartmentId
                                      && x.DepartmentHeadId == 1);

                    // 获取有效通过数（同部门+通过状态）
                    var approvedCount =  recordRep.GetAll().Result
                        .Count(x => x.LeaveId == request.LeaveId
                                      && x.DepartmentId == request.DepartmentId
                                      && x.DepartmentHeadId == 1
                                      && x.Status == ApproveStatus.通过.ToString());

                    // 判断是否全部审批通过
                    if (approvedCount  == totalLeaders && request.Status == ApproveStatus.通过.ToString())
                    {
                        application.Status = 2; // 更新为部门已审批状态
                    }
                    else if (request.Status == ApproveStatus.未通过.ToString())
                    {
                        application.Status = 3; // 直接拒绝
                    }
                }

                // 5. 总裁审批逻辑
                if (request.DepartmentHeadId == 2 && application.Status == 2)
                {
                    application.Status = request.Status == ApproveStatus.通过.ToString() ? 3 : 3;
                }

                // 6. 更新申请状态
                await leaveappRep.Update(application);

                result.Code = APIEnum.操作成功;
                result.Msg = "审批操作已完成";
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.操作失败;
                result.Msg = $"审批失败：{ex.Message}";
                // 记录日志
                // _logger.LogError(ex, "审批流程异常 LeaveId:{LeaveId}", request.LeaveId);
            }

            return result;
        }
    }
}





